package cn.yuanqiao.archive.danganzhengli.utils;/**
 * @author 赵常飞
 * @date 2024/3/25 19:09
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 *@Author: 赵常飞
 *@Date: 2024/3/25 19:09
 *@Description:
 *@Note:
 */

public class webServiceHttp {
    public static String sendWebService(String url,String isClass,String isMethod,StringBuffer paramsXml) throws Exception {
        //传过来的xml格式
        String xml = paramsXml.toString();
        if (xml==null){
            return "传入xml参数不能为空！";
        }
        URL sopul = new URL(url);
        //获取连接
        URLConnection connention = sopul.openConnection();
        //缓存设置
        connention.setUseCaches(false);
        //设置输入输出，新创建的connection默认是没有读写权限的
        connention.setDoInput(true);
        connention.setDoOutput(true);
        //设置请求头
        connention.setRequestProperty("Content-Length",xml.length()+"");
        //这里设置请求头类型为xml,传统http请求的是超文本传输格式text/html
        connention.setRequestProperty("Content-Type","text/xml; charset=utf-8");
        //调用的类名，方法名
        connention.setRequestProperty(isClass,isMethod);
        //这里如果携带token设置token,没传则不设置
        // if (token!=null){
        //     connention.setRequestProperty("Authorization","Bearer "+token);
        // }
        OutputStream os = connention.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os,"utf-8");
        //写入传过来的xml文件格式
        osw.write(xml);
        //释放资源
        osw.flush();
        osw.close();
        //下面获取webservice返回过来的流
        InputStream is = connention.getInputStream();
        if (is!=null){
            byte[] bytes = new byte[0];
            bytes=new byte[is.available()];
            is.read(bytes);
            //将字节数组转换为字符串输出
            String outXml = new String(bytes,"UTF-8");
            //webservice返回为xml,在此处解析为json,只取返回值
            XmlMapper xmlMapper = new XmlMapper();
            JsonNode jsonNode = xmlMapper.readValue(outXml, JsonNode.class);
            ObjectMapper jsonMapper = new ObjectMapper();
            String json = jsonMapper.writeValueAsString(jsonNode);
            JSONObject jsonObject = JSON.parseObject(json);
            return jsonObject.getJSONObject("Body").getJSONObject(isMethod+"Response").getJSONObject("return").toString();
        }
        return null;
    }
}
